<?php

namespace addon\lian\shop\controller;

use addon\lian\model\LianGoods;
use addon\lian\model\LianLevel as LianLevelModel;
use addon\lian\model\sqlmodel\GoodsModel;
use addon\lian\model\sqlmodel\GoodsSkuModel;
use app\shop\controller\BaseShop;
use addon\lian\model\sqlmodel\LianGoodsModel;
use think\facade\Db;
use addon\lian\model\Config as LianConfigModel;
use think\facade\Log;

/**
 *  链动商品
 */
class Goods extends BaseShop
{

    /**
     * 商品列表
     */
    public function lists()
    {
        $model = new \app\model\goods\Goods();

        if (request()->isJson()) {

            $page_index = input('page', 1);
            $page_size = input('page_size', PAGE_LIST_ROWS);
            $condition = [
                [ 'is_delete', '=', 0 ],
                [ 'site_id', '=', $this->site_id ]
            ];
            $search_text_type = input('search_text_type', 'goods_name');//店铺名称或者商品名称
            $search_text = input('search_text', '');
            $goods_class = input('goods_class', '');//商品种类
            $goods_state = input('goods_state', '');//商品状态
            $category_id = input('category_id', '');//分类ID
            $is_lian = input('is_lian', '');
            $start_sale = input('start_sale', 0);
            $end_sale = input('end_sale', 0);
            if (!empty($search_text)) {
                $condition[] = [ $search_text_type, 'like', '%' . $search_text . '%' ];
            }

            if ($is_lian !== '') {
                $condition[] = [ 'is_lian', '=', $is_lian ];
            }
            if (!empty($start_sale)) $condition[] = [ 'sale_num', '>=', $start_sale ];
            if (!empty($end_sale)) $condition[] = [ 'sale_num', '<=', $end_sale ];

            if ($goods_class !== '') {
                $condition[] = [ 'goods_class', '=', $goods_class ];
            }

            if ($goods_state !== '') {
                $condition[] = [ 'goods_state', '=', $goods_state ];
            }

            if (!empty($category_id)) {
                $condition[] = [ 'category_id', 'like', '%,' . $category_id . ',%' ];
            }
            // $list = $model->getGoodsPageList($condition, $page_index, $page_size);
            $list = (new LianGoods)->getPage($condition, $this->site_id, $page_index, $page_size);
            return $list;
        } else {

            return $this->fetch('goods/lists');
        }
    }

    public function detail()
    {
        try{
            $goods_id = input('goods_id');
            $lian_leve_model = new LianLevelModel();

            $lian_goods = (new LianGoodsModel())
                ->where([['site_id', '=', $this->site_id], ['goods_id', '=', $goods_id]])
                ->with([
                    'goodsSku' => function ($query) {
                        $query->withField('sku_id, sku_name, goods_id, price');
                    },
                    'goods' => function ($query) {
                        $query->withField('goods_id, goods_name, goods_image, goods_stock, sale_num, sort, create_time, goods_state');
                    }
                ])
                ->findOrEmpty()->toArray();
            
            // 处理reward_set数据，确保它是数组形式
            $reward_set = [];
            if (!empty($lian_goods['reward_set'])) {
                if (is_string($lian_goods['reward_set'])) {
                    $reward_set = json_decode($lian_goods['reward_set'], true);
                } else if (is_array($lian_goods['reward_set'])) {
                    $reward_set = $lian_goods['reward_set'];
                }
            }
            
            // 添加调试日志
            Log::info('处理后的reward_set: ' . json_encode($reward_set, JSON_UNESCAPED_UNICODE));

            $goods_info = $lian_goods;
            $goods_info['goods_image'] = explode(',', $goods_info['goods']['goods_image']);
            
            $lian_level = $lian_leve_model->getLevelList([['site_id', '=', $this->site_id]]);

            if (!empty($lian_goods['goodsSku'])) {
                if (isset($lian_goods['goodsSku']['sku_id'])) {
                    $goods_info['sku_list'] = [$lian_goods['goodsSku']];
                } else {
                    $goods_info['sku_list'] = $lian_goods['goodsSku'];
                }
            } else {
                $goods_info['sku_list'] = [];
            }
            
            foreach ($goods_info['sku_list'] as $key => &$sku) {
                $sku_id = $sku['sku_id'];
                if (isset($reward_set[$sku_id])) {
                    // 直接使用reward_set中的数据
                    $sku_reward = $reward_set[$sku_id];
                    
                    // 初始化佣金规则
                    $commission_rules = [
                        'calculate_price' => $sku_reward['calculate_price'] ?? $sku['price']
                    ];
                    
                    // 处理各个级别的奖励规则
                    foreach ($lian_level['data'] as $level) {
                        $level_id = (string)$level['level_id'];
                        if (isset($sku_reward[$level_id])) {
                            $commission_rules[$level_id] = $sku_reward[$level_id];
                        }
                    }
                    
                    $sku['commission_rules'] = $commission_rules;
                    Log::info('SKU ' . $sku_id . ' 的佣金规则: ' . json_encode($commission_rules, JSON_UNESCAPED_UNICODE));
                } else {
                    Log::info('SKU ' . $sku_id . ' 没有找到佣金规则');
                    $sku['commission_rules'] = [];
                }
            }
            unset($sku);

            $goods_info['goods_name'] = $lian_goods['goods']['goods_name'];
            
            // 添加调试日志
            Log::info('最终goods_info结构：' . json_encode($goods_info, JSON_UNESCAPED_UNICODE));
            
            $this->assign('lian_level', $lian_level['data']);
            $this->assign('goods_info', $goods_info);

            $lian_config_model = new LianConfigModel();
            $lian_config = $lian_config_model->getLianBasicsConfig($this->site_id)[ 'data' ] ?? [];
            $this->assign('lian_config', $lian_config[ 'value' ] ?? []);
            
            return $this->fetch('goods/detail');
        }catch(\Exception $e){
            Log::write('1111:' . $e->getMessage(). '-line:'.$e->getLine() . '--file:' . $e->getFile());
        }
    }


    /**
     * 修改链动状态
     */
    public function modify()
    {
        if (request()->isJson()) {
            $lian_goods_model = new LianGoods();

            // 获取goods_id参数（单个商品情况）
            $goods_id = input('goods_id', '');
            $is_lian = input('is_lian', 0);

            Log::info('modifyGoodsIsLian' . '--goods_ids:' . $goods_id . '--is_lian:' . $is_lian . '--site_id:' . $this->site_id);
            
            // 确保goods_id是数组形式，即使只有一个ID
            if (!empty($goods_id)) {
                return $lian_goods_model->modifyGoodsIsLian([$goods_id], $is_lian, $this->site_id);
            }
            
            return $this->error('商品ID不能为空');
        }
    }

    /**
     * 批量设置是否参与链动
     * @return array
     */
    public function setGoodsIsLian()
    {
        if (request()->isJson()) {
            $lian_goods_model = new LianGoodsModel();
            $goods_ids = input('goods_ids', '');
            $is_lian = input('is_lian', 0);
            return $lian_goods_model->modifyGoodsIsLian($goods_ids, $is_lian, $this->site_id);
        }
    }


    /**
     * 链动商品奖励详情
     */
    public function goodsCommission(int $id)
    {
        return $this->success((new LianGoods())->getGoodsCommission($id, $this->site_id));
    }


    /**
     * 商品链动配置
     */
    public function config(){
        Log::info('config11');
        $goods_id = input('goods_id');

        $goods_info = (new LianGoodsModel())->where([['site_id', '=', $this->site_id], ['goods_id', '=', $goods_id]])
            ->with([
                'goodsSku' => function ($query) {
                    $query->withField('sku_id, sku_name, goods_id, price, cost_price');
                },
                'goods' => function ($query) {
                    $query->withField('goods_id, goods_name, goods_image, goods_stock, sale_num, sort, create_time, goods_state');
                }
            ])
            ->findOrEmpty()->toArray();

        // 设置默认值，避免未定义数组索引错误
        $goods_info['is_lian'] = $goods_info['is_lian'] ?? 0;
        $goods_info['is_rule'] = $goods_info['is_rule'] ?? 1;
        $goods_info['goods_image'] = isset($goods_info['goods']['goods_image']) ? 
            explode(',', $goods_info['goods']['goods_image']) : [];
        $goods_info['goods_name'] = $goods_info['goods']['goods_name'] ?? '';
        
        // 确保goodsSku始终是数组形式
        if (isset($goods_info['goodsSku']['sku_id'])) {
            // 如果是单个SKU对象，转为数组形式
            $goods_info['sku_data'] = [$goods_info['goodsSku']];
        } else {
            $goods_info['sku_data'] = $goods_info['goodsSku'] ?? [];
        }

        // 处理每个SKU，确保必要的字段存在
        foreach ($goods_info['sku_data'] as &$sku) {
            $sku['price'] = $sku['price'] ?? '0.00';
            $sku['cost_price'] = $sku['cost_price'] ?? '0.00';
            $sku['sku_name'] = $sku['sku_name'] ?? '';
            $sku['lian_price'] = $sku['lian_price'] ?? '';
        }
        unset($sku);

        // 解析reward_set
        $reward_set = [];
        if (!empty($goods_info['reward_set'])) {
            if (is_string($goods_info['reward_set'])) {
                $reward_set = json_decode($goods_info['reward_set'], true);
            } else {
                $reward_set = $goods_info['reward_set'];
            }
            
            // 确保每个SKU的奖励设置中包含金额字段
            if (is_array($reward_set)) {
                foreach ($reward_set as $sku_id => &$sku_reward) {
                    if (is_array($sku_reward)) {
                        foreach ($sku_reward as $level_id => &$level_reward) {
                            if (is_array($level_reward) && !is_numeric($level_id)) {
                                // 确保奖励金额字段存在
                                $level_reward['recommend_money'] = $level_reward['recommend_money'] ?? '0';
                                $level_reward['see_money'] = $level_reward['see_money'] ?? '0';
                                $level_reward['cultivate_money'] = $level_reward['cultivate_money'] ?? '0';
                            }
                        }
                        unset($level_reward);
                    }
                }
                unset($sku_reward);
            }
        }
        $goods_info['reward_set'] = $reward_set;

        // 获取链动等级
        $lian_level_model = new LianLevelModel();
        $lian_level = $lian_level_model->getLevelList([['site_id', '=', $this->site_id]]);
        $this->assign('lian_level', $lian_level['data']);

        if(request()->isJson()){
            Log::info('config');
            $is_lian = input('is_lian', 0);
            $is_rule = input('is_rule', 0);
            $lian_price = input('lian_price', 0);
            $reward_set = input('reward_set', []);
            $skuList = input('skuList', []);

            $data = [
                'is_lian' => $is_lian,
                'is_rule' => $is_rule,
                'lian_price' => $lian_price,
                'reward_set' => json_encode($reward_set, JSON_UNESCAPED_UNICODE),
                'skuList' => $skuList
            ];

            return (new LianGoods())->editLianGoods($goods_id, $data, $this->site_id);
        }

        $this->assign('goods_info', $goods_info);
        return $this->fetch('goods/config');
    }
}